// Yang Shuai  Copyright (c) 2022 https://yby6.com.
// Copyright (c) 2022. Yangbuyi, personal projects are not allowed to be commercialized without permission.
// Please keep the information of the original author of the code. Thank you
//

package com.leetroll.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.leetroll.app.service.SmsService;
import com.leetroll.common.utils.StringUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.leetroll.common.constant.AliyunConstant.*;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    /**
     * 应用APPID
     */
    @Value("${tencent.smsSdkAppId}")
    private String smsSdkAppId;
    /**
     * 短信签名名称
     */
    @Value("${tencent.signName}")
    private String signName;

    /**
     * 正文模板ID
     * 短信发送之类需要
     */
    @Value("${tencent.templateId}")
    private String templateId;
    /**
     * 腾讯云access key
     */
    @Value("${tencent.accessKey}")
    private String keyId;
    /**
     * 腾讯云key 密钥访问秘密
     */
    @Value("${tencent.accessSecret}")
    private String keySecret;

    /**
     * 发送短信
     */
    @Override
    public boolean send(String phone, Map<String, Object> param) {
        return sendPhone(phone, "SMS_169111508", param);
    }

    /**
     * 腾讯云短信发送
     *
     * @param code   验证码 (4)
     * @param phones 手机号 批量
     */
    @Override
    public boolean sendTencentSms(String code, String... phones) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(keyId, keySecret);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            // 电话号码
            req.setPhoneNumberSet(phones);

            req.setSmsSdkAppId(smsSdkAppId);
            req.setSignName(signName);
            req.setTemplateId(templateId);

            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            String toJsonString = SendSmsResponse.toJsonString(resp);
            if (toJsonString.contains("Code") && toJsonString.contains("Ok") && toJsonString.contains("send success")) {
                log.info("短信发送成功： {}", toJsonString);
                return true;
            }
            System.out.println(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info("短信发送失败： {}", e.toString());
        }
        return false;
    }


    /**
     * 发送短信
     *
     * @param phoneNumbers 电话号码
     * @param templateCode 模板代码
     * @param param        参数
     * @return 成功true
     */
    public static boolean sendPhone(String phoneNumbers, String templateCode, Map<String, Object> param) {
        if (StringUtils.isEmpty(phoneNumbers)) {
            return false;
        }
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY, ACCESS_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "签名");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}